import distributedKVStore from '@ohos.data.distributedKVStore';
import promptAction from '@ohos.promptAction';

export const KEY_LOGIN_TOKEN = "普通token"

export const KEY_API_TOKEN = "APItoken"

export const KEY_REFRESH_CODE = "刷新token的code"

export const KEY_TOKEN_TYPE = "TOKEN的类型"

export class KvManager {
  public kvStore;
  public context;

  constructor(context) {
    this.context = context

  }

  public async initKvManager() {
    const kvManagerConfig = {
      context: this.context,
      bundleName: 'com.zcitc.cloudhousehelper'
    };
    const options = {
      createIfMissing: true, // 当数据库文件不存在时是否创建数据库，默认创建
      encrypt: false, // 设置数据库文件是否加密，默认不加密
      backup: false, // 设置数据库文件是否备份，默认备份
      kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 设置要创建的数据库类型，默认为多设备协同数据库
      securityLevel: distributedKVStore.SecurityLevel.S2 // 设置数据库安全级别
    };
    try {
      console.info('tagtagtagtagtagtagtag=a===', 'await distributedKVStore开始');
      this.kvStore = await distributedKVStore.createKVManager(kvManagerConfig).getKVStore('storeId', options)
      // distributedKVStore.createKVManager(kvManagerConfig).getKVStore('storeId', options, (err, store) => {
      //   if (err) {
      //     console.error('tagtagtagtagtag=a==', `tagtagtagtagtag=aFailed to get KVStore.code is ${err.code},message is ${err.message}`);
      //     return;
      //   }
      //   console.info('tagtagtagtagtag=a==', "tagtagtagtagtag=aSucceeded in getting KVStore");
      //   this.kvStore = store
      // });
      console.info('tagtagtagtagtagtagtag=a===', 'await distributedKVStore结束');

    } catch (e) {
      console.error('tagtagtagtagtag=a==', `tagtagtagtagtag=aFailed to create KVManager. Code:${e.code},message:${e.message}`);
    }
  }

  public async putKv(name: string, value: string) {
    if (this.kvStore) {
      try {
        console.info('tagtagtagtagtagtagtag=a===', 'putKv开始保存==name=' + name);
        console.info('tagtagtagtagtagtagtag=a===', 'putKv开始保存==value=' + value);
        await this.kvStore.put(name, value)
        console.info('tagtagtagtagtagtagtag=a===', 'putKv保存结束==name=' + name);
        // this.kvStore.put(name, value).then((data) => {
        //   console.info('tagtagtagtagtag=a==', `Succeeded in putting.data=${data}`);
        // }).catch((err) => {
        //   console.error('tagtagtagtagtag=a==', `Failed to put.code is ${err.code},message is ${err.message}`);
        // });
      } catch (e) {
        console.error('tagtagtagtagtag=a==', `An unexpected error occurred.code is ${e.code},message is ${e.message}`);
      }
    }

    // const err = await this.kvStore.put(name, value)
    // if (err !== undefined) {
    //   console.error('tagtagtagtagtag=a==', 'Failed to put data. name=' + name);
    //   return;
    // }
    // console.info('tagtagtagtagtag=a===', 'Succeeded in putting data.name=' + name);

  }


  public async getKv(name: string): Promise<string> {
    if (this.kvStore) {

      try {
        const data = await this.kvStore.get(name)

        return data
      } catch (e) {
        console.error('tagtagtagtagtag=a===', `Failed to get data. Code:${e.code},message:${e.message}`);
        console.error(`Failed to get data. Code:${e.code},message:${e.message}`);
        console.info('tagtagtagtagtagtagtag=a===', 'getKv获取失败==e=' + JSON.stringify(e));
        return ''
      }
    }

    // try {
    //   this.kvStore.get(name, (err, data) => {
    //     console.info('tagtagtagtagtag=a===', ' name=' + name);
    //     if (err !== undefined) {
    //       console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
    //       console.error('tagtagtagtagtag=a===', `Failed to get data. Code:${err.code},message:${err.message}`);
    //       callback('');
    //     } else {
    //       console.info(`Succeeded in getting data. data:${data}`);
    //       callback(data)
    //     }
    //
    //   });
    // } catch (e) {
    //   console.error('tagtagtagtagtag=a===', `Failed to get data. Code:${e.code},message:${e.message}`);
    //   console.error(`Failed to get data. Code:${e.code},message:${e.message}`);
    //   callback('')
    //
    // }
  }

  public deleteKv(name: string) {

    try {
      this.kvStore.delete(name, (err) => {
        if (err !== undefined) {
          console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
          return;
        }

      });
    } catch (e) {

      console.error(`Failed to get data. Code:${e.code},message:${e.message}`);
      return "";
    }
  }

  public async getHeader(isApiTolen: boolean): Promise<object> {

    const type = await this.getKv(KEY_TOKEN_TYPE)
    const token = isApiTolen ? await this.getKv(KEY_API_TOKEN) : await this.getKv(KEY_LOGIN_TOKEN)
    if(!isApiTolen){
      if(!token){
        return null
      }
    }
      const header = {
        'Content-Type': 'application/json',
        'Authorization': type + ' ' + token
      }
      console.info('tagtagtagtagtag=a===', 'getHeader header=' + JSON.stringify(header));
      return header


  }
  public async getWebTolen(): Promise<string> {

    const apiToken = await this.getKv(KEY_API_TOKEN)
    const token =  await this.getKv(KEY_LOGIN_TOKEN)
    if(apiToken){
      return apiToken
    }

    return token


  }
  //
  // public getTokenType(callback: (d: string) => void) {
  //
  //   try {
  //     this.kvStore.get(KEY_TOKEN_TYPE, (err, data) => {
  //       if (err !== undefined) {
  //         console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
  //
  //         callback('Basic');
  //       } else {
  //         console.info(`Succeeded in getting data. data:${data}`);
  //         callback(data)
  //       }
  //
  //     });
  //   } catch (e) {
  //     console.error(`Failed to get data. Code:${e.code},message:${e.message}`);
  //     callback('Basic')
  //
  //   }
  // }
  //
  // public getLoginToken(callback: (d: string) => void) {
  //   this.getKv(KEY_LOGIN_TOKEN, callback)
  //
  // }
  //
  // public getApiToken(callback: (d: string) => void) {
  //   this.getKv(KEY_API_TOKEN, callback)
  //
  // }
  //
  // public getToken(callback: (d: string) => void) {
  //
  //   this.getApiToken(apiToken => {
  //     if (apiToken !== '') {
  //       callback(apiToken)
  //     } else {
  //       this.getLoginToken(loginToken => {
  //         callback(loginToken)
  //       })
  //     }
  //   })
  // }
  //
  // public isLogin(callback: (d: boolean) => void) {
  //   this.getApiToken(apiToken => {
  //     if (apiToken !== '') {
  //       callback(true)
  //     } else {
  //       this.getLoginToken(loginToken => {
  //         callback(false)
  //       })
  //     }
  //   })
  // }
}